<!-- src/views/blog/components/BlogEditModal.vue -->
<template>
	<n-modal v-model:show="showModal" preset="card" :style="{ width: '80%' }" :title="isEditMode ? '编辑博客' : '新增博客'"
		:mask-closable="false" :close-on-esc="false" @close="handleClose">
		<n-spin :show="loading">
			<n-form ref="formRef" :model="formValue" :rules="rules" label-placement="left" label-width="100">
				<n-form-item label="标题" path="title">
					<n-input v-model:value="formValue.title" placeholder="请输入博客标题" />
				</n-form-item>

				<n-form-item label="类型" path="type">
					<n-radio-group v-model:value="formValue.type">
						<n-space>
							<n-radio v-for="option in blogTypeOptions" :key="option.value" :value="option.value">
								{{ option.label }}
							</n-radio>
						</n-space>
					</n-radio-group>
				</n-form-item>

				<n-form-item label="摘要" path="summary">
					<n-input v-model:value="formValue.summary" type="textarea" placeholder="请输入博客摘要" />
				</n-form-item>

				<n-form-item label="内容" path="content">
					<Vditor v-model="formValue.content" :height="400" placeholder="请输入博客内容" />
				</n-form-item>
			</n-form>
		</n-spin>

		<template #footer>
			<n-space justify="end">
				<n-button @click="handleClose">取消</n-button>
				<n-button type="primary" @click="handleSubmit" :loading="submitLoading">保存</n-button>
			</n-space>
		</template>
	</n-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { FormInst, useMessage, NSpace, NRadio, NRadioGroup } from 'naive-ui';
import {
	blogApi,
	ArticleType,
	ArticleTypeLabels,
	ArticleStatus,
	type AddOrUpdateBlogRequest,
	type BlogDtoBlogDetailDto
} from '@/service/api/blog';
import Vditor from '@/components/common/vditor.vue';

const props = defineProps<{
	show: boolean;
	currentBlogId?: number | undefined | null;
}>();

const emit = defineEmits<{
	(e: 'update:show', value: boolean): void;
	(e: 'save'): void;
	(e: 'close'): void;
}>();

const message = useMessage();
const formRef = ref<FormInst | null>(null);
const submitLoading = ref(false);
const loading = ref(false);

// 判断是否为编辑模式
const isEditMode = computed(() => {
	return !!props.currentBlogId;
});

// 博客类型选项
const blogTypeOptions = Object.entries(ArticleType)
	.filter(([, value]) => typeof value === 'number')
	.map(([label, value]) => ({
		label: ArticleTypeLabels[value as ArticleType],
		value: value as ArticleType
	}));

// 表单数据
const formValue = ref<BlogDtoBlogDetailDto>({
	id: undefined as number | undefined,
	title: '',
	type: undefined as ArticleType | undefined, // 移除 number 类型
	summary: '',
	content: '',
	status: ArticleStatus.Draft,
});

// 表单验证规则
const rules = {
	title: {
		required: true,
		message: '请输入博客标题',
		trigger: 'blur'
	},
	type: {
		required: true,
		validator(rule: any, value: any) {
			if (value === null || value === undefined) {
				return new Error('请选择博客类型');
			}
			return true;
		},
		trigger: 'change'
	},
	summary: {
		required: true,
		message: '请输入博客摘要',
		trigger: 'blur'
	},
	content: {
		required: true,
		message: '请输入博客内容',
		trigger: 'blur'
	}
};

// 控制弹窗显示
const showModal = computed({
	get() {
		return props.show;
	},
	set(value) {
		emit('update:show', value);
	}
});

// 监听博客数据变化
watch(() => props.currentBlogId, async (newVal) => {
	if (newVal) {
		// 编辑模式：获取博客详情
		loading.value = true;
		try {
			const detailData = await blogApi.GetBlogById(newVal);
			formValue.value = {
				id: detailData.id,
				title: detailData.title || '',
				type: detailData.type !== undefined ? detailData.type : undefined,
				summary: detailData.summary || '',
				content: detailData.content || '',
				status: detailData.status,
			};
		} catch (error) {
			message.error('获取博客详情失败');
			console.error(error);
		} finally {
			loading.value = false;
		}
	} else {
		// 新增模式：重置表单
		formValue.value = {
			id: undefined,
			title: '',
			type: undefined,
			summary: '',
			content: '',
			publicationTime: null,
			status: ArticleStatus.Draft,
		};
	}
}, { immediate: true });

// 关闭弹窗
const handleClose = () => {
	emit('close');
	emit('update:show', false);
};

// 提交表单
const handleSubmit = (e: MouseEvent) => {
	e.preventDefault();
	formRef.value?.validate(async (errors) => {
		if (!errors) {
			submitLoading.value = true;
			try {
				// 构造请求参数
				const requestData: AddOrUpdateBlogRequest = {
					id: formValue.value.id,
					title: formValue.value.title ?? '',
					type: formValue.value.type!, // 类型断言
					summary: formValue.value.summary ?? '',
					content: formValue.value.content ?? ''
				};

				// 调用保存接口
				const result = await blogApi.AddOrUpdateBlog(requestData);

				if (result) {
					message.success(`${isEditMode.value ? '编辑' : '新增'}博客成功`);

					emit('save');
					handleClose();
				} else {
					message.error(`${isEditMode.value ? '编辑' : '新增'}博客失败`);
				}
			} catch (error) {
				message.error(`${isEditMode.value ? '编辑' : '新增'}博客失败`);
				console.error(error);
			} finally {
				submitLoading.value = false;
			}
		} else {
			message.error('请填写完整信息');
		}
	});
};
</script>
